package com.yk.faceapplication.util;

import android.app.Activity;
import android.content.Context;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.yk.faceapplication.MyApplication;
import com.yk.faceapplication.callback.RequestCallback;
import com.yk.faceapplication.callback.UploadCallback;
import com.yk.faceapplication.http.MultipartRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

/**
 * Created by yk_2018/1/12_16:58
 */

public class RequestUtil {
    public static void request(final Context act, final String url, final RequestCallback callback, Map<String, ?> map) {

                LogDebugger.info("url:" + url);
        LogDebugger.info("map:" + map);
        final Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
//                LogDebugger.info("url:" + url);
                LogDebugger.info("data:" + jsonObject);
                try {
                    if ("000000".equals(jsonObject.getString("code"))) {
                        //                        LogDebugger.info("success:" + jsonObject.getString("code"));
                        callback.success(jsonObject);
                    } else {
                        if (jsonObject.has("msg")) {
                            Toast.makeText(act, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                            callback.fail(new VolleyError());
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        };
        final Response.ErrorListener eListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                callback.fail(volleyError);
            }
        };
        final String jsonObject = com.alibaba.fastjson.JSONObject.toJSONString(map);
        try {
            JSONObject jObj = new JSONObject(jsonObject);
            LogDebugger.info("jObj:" + jObj);
            JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, jObj, sListener, eListener) {
                @Override
                protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                    JSONObject jsonObject;
                    try {
                        jsonObject = new JSONObject(new String(response.data, "UTF-8"));
                        return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        return Response.error(new ParseError(e));
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return Response.error(new ParseError(e));
                    }
                }
            };
            ((MyApplication) act.getApplicationContext()).getrQueue().add(req);
        } catch (Exception e) {

        }
    }

    public static void request(final String url, String jsonStr) {
        LogDebugger.info(url);
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");//数据类型为json格式，
        RequestBody body = RequestBody.create(JSON, jsonStr);
        okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(body).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                LogDebugger.info(new String(response.body().bytes()));
            }
        });//此处省略回调方法。
    }


    public static void getRequest(final Context act, final String url, final RequestCallback callback) {

                        LogDebugger.info("url:" + url);
        //        LogDebugger.info("map:" + map);
        final Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
//                LogDebugger.info("url:" + url);
                LogDebugger.info("data:" + jsonObject);
                try {
                    if ("000000".equals(jsonObject.getString("code"))) {
                        //                        LogDebugger.info("success:" + jsonObject.getString("code"));
                        callback.success(jsonObject);
                    } else {
                        if (jsonObject.has("msg")) {
                            Toast.makeText(act, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        };
        final Response.ErrorListener eListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                LogDebugger.info("onErrorResponse:" + volleyError.getMessage());
                callback.fail(volleyError);
            }
        };
        try {
            JSONObject jObj = new JSONObject();
            LogDebugger.info("jObj:" + jObj);
            JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, jObj, sListener, eListener) {
                @Override
                protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                    JSONObject jsonObject;
                    try {
                        jsonObject = new JSONObject(new String(response.data, "UTF-8"));
                        return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        return Response.error(new ParseError(e));
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return Response.error(new ParseError(e));
                    }
                }
            };
            ((MyApplication) act.getApplicationContext()).getrQueue().add(req);
        } catch (Exception e) {

        }
    }

    public static void uploadFile(final Activity act, final UploadCallback callback, String filePartName, File file, Map<String, String> params) {

        final Response.Listener<String> sListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String jsonObject) {
                LogDebugger.info("onResponse:" + jsonObject);
                callback.success(jsonObject);
            }
        };
        final Response.ErrorListener eListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
                callback.fail(volleyError);
            }
        };
        MyApplication mApplication = ((MyApplication) act.getApplicationContext());
        MultipartRequest req = new MultipartRequest("http://filegateway.allinpaycard.cn/upload?token=" + mApplication.getToken(), eListener, sListener, filePartName, file, params);
        mApplication.getrQueue().add(req);
    }
}
